layui.define(['table', 'form', 'admin', 'upload'], function (exports) {
    var $ = layui.$
        , table = layui.table
        , form = layui.form
        , upload = layui.upload
        , admin = layui.admin;

    // 渠道列表
    table.render({
        elem: '#LAY-regsource-manage'
        , url: '/admin/regsource/getlist'
        , totalRow: true
        , cols: [[
            // {type: 'checkbox', fixed: true}
            { field: 'id', width: 80, title: 'ID', totalRowText: '统计', fixed: true }
            , { field: 'source_key', width: 120, title: '渠道标识', fixed: true }
            , { field: 'source_name', width: 150, title: '渠道名称' }
            , { field: 'spec', width: 90, title: '特殊渠道', templet: function (d) {return d.spec? '是':'-';}}
            , { field: 'joycircle', width: 90, title: '悦动圈渠道', templet: function (d) {return d.joycircle? '是':'-';}}
            , {
                field: 'down_total', width: 120, title: '下载数量', templet: function (d) {
                    let app_download_total = 0;
                    if (d.appdownload) {
                        app_download_total = d.appdownload.total;
                    }

                    return '<a style="text-underline: auto;color:#1E9FFF;cursor: pointer" lay-event="showAppdownload">' + app_download_total + '</a>'
                }
            }
            , {
                field: 'register', width: 120, title: '注册人数', sort: true, templet: function (d) {
                    return '<a style="text-underline: auto;color:#1E9FFF;cursor: pointer" lay-event="showUserList">' + d.register + '</a>'
                }
            }
            // , { field: 'valid_user', width: 120, title: '有效用户', totalRowText: '' }
            , {
                field: '', title: '平均次日留存率', width: 140, templet: function (d) {
                    return d.retention + '%'
                }
            }
            , {
                field: '', title: '设备', width: 100, templet: function (d) {
                    switch (d.device) {
                        case 1:
                            return "<span style='color:#009688'>安卓</span>";
                        case 2:
                            return "<span style='color:#1E9FFF'>苹果</span>";
                        case 3:
                            return "<span style='color:#FFB800'>PC端</span>";
                    }
                    return '';
                }
            }
            , {
                field: '', title: '地址', minWidth: 200, templet: function (d) {
                    if (!d.url) {
                        return '';
                    }
                    return '<a href="javascript:;" data-clipboard-text="" class="layui-btn layui-btn-warm layui-btn-xs copyCoverUrl" style="margin-right:10px;" title="点击复制" lay-event="copyCoverUrl">复制</a>' + d.url;
                }
            }
            // , {
            //     field: '', title: '状态', width: 100, templet: function (d) {
            //         return d.status == 1 ? "<span style='color:#009688'>正常</span>" : "冻结"
            //     }
            // }
            , { field: 'create_time', width: 180, title: '创建时间' }
            , { title: '操作', width: 220, align: 'center', fixed: 'right', toolbar: '#table-regsource-operate' }
        ]]
        //主要利用回调渲染
        , done: function (res, curr, count) {
            if (res.statis) {
                this.elem.next().find('.layui-table-total td[data-field="register"] .layui-table-cell').text(res.statis.register);
                this.elem.next().find('.layui-table-total td[data-field="valid_user"] .layui-table-cell').text(res.statis.valid_user);
            }
        }
        , page: true
        , limit: 20
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true
    });


    //渠道列表工具条监听
    table.on('tool(LAY-regsource-manage)', function (obj) {
        // 复制url地址
        if (obj.event === 'copyCoverUrl') {
            var link_url = obj.data.url;
            if (!link_url) {
                return layer.msg('连接错误，复制失败');
            }

            $(".copyCoverUrl").attr("data-clipboard-text", link_url);
            var clipboard = new ClipboardJS('.copyCoverUrl');
            clipboard.on('success', function (e) {
                layer.msg('复制成功');
                clipboard.destroy();  //解决多次弹窗
                e.clearSelection();
            });
        } else if (obj.event === 'setstatus') {
            var str = obj.data.status == 0 ? "解封" : "封禁";
            layer.confirm('确定要' + str + '吗？', function (index) {
                layer.load();
                var status = obj.data.status == 0 ? 1 : 0;
                admin.req({
                    url: '/admin/regsource/set_status'
                    , data: { id: obj.data.id, status: status }
                    , success(res) {
                        layer.closeAll("loading");
                        if (res.code == 0) {
                            table.reload("LAY-regsource-manage");
                            layer.msg(res.msg, { icon: 1 });
                        }
                    }
                    , complete: function () {
                        layer.closeAll("loading");
                    },
                });
            });
        } else if (obj.event === 'edit') {
            layer.open({
                type: 2
                , title: '编辑渠道'
                , content: '/admin/regsource/edit?id=' + obj.data.id
                , maxmin: true
                , area: ['550px', '550px']
            });
        } else if (obj.event === 'everyday') {
            let index = layer.open({
                type: 2
                , title: '渠道每日数据'
                , content: '/admin/regsource/everyday?source_key=' + obj.data.source_key
                , maxmin: true
                , area: ['700px', '500px']
            });
            layer.full(index);
        } else if (obj.event === 'showUserList') {
            let index = layer.open({
                type: 2
                , title: '渠道用户列表'
                , content: '/admin/user/index?source_key=' + obj.data.source_key
                , maxmin: true
                , area: ['700px', '500px']
            });
            layer.full(index);
        } else if (obj.event === 'showAppdownload') {
            let index = layer.open({
                type: 2
                , title: '渠道下载列表'
                , content: '/admin/appdownload/index?source=' + obj.data.source_key
                , maxmin: true
                , area: ['700px', '500px']
            });
            layer.full(index);
        } else if (obj.event === 'del') { 
            layer.confirm('确定删除吗？', function (index) {
                admin.req({
                    url: '/admin/regsource/del'
                    , data: { id: obj.data.id}
                    , success(res) {
                        layer.closeAll("loading");
                        if (res.code == 0) {
                            table.reload("LAY-regsource-manage");
                            layer.msg(res.msg, { icon: 1 });
                        }
                    }
                    , complete: function () {
                        layer.closeAll("loading");
                    },
                });
            });
          }

    });

    // 时间类型选择
    $('.timeChoice button').click(function () {
        $('.timeChoice button').removeClass('btn_danger');
        $(this).addClass('btn_danger');
        $('#start_time_input').val('');
        $('#end_time_input').val('');
        //执行重载
        table.reload('LAY-source-everyday-manage', {
            where: {
                type: $('.timeChoice .btn_danger').data('type')
                , start_time: $('#start_time_input').val()
                , end_time: $('#end_time_input').val()
            }
            , page: {
                curr: 1   //默认从第一页开始搜索
            },
        });
    })


    // 渠道每日数据列表
    table.render({
        elem: '#LAY-source-everyday-manage'
        , url: '/admin/regsource/everyday_list?source_key=' + $('#sourceKey').val()
        , totalRow: true
        , where: {
            type: $('.timeChoice .btn_danger').data('type')
            , start_time: $('#start_time_input').val()
            , end_time: $('#end_time_input').val()
        }
        , cols: [[
            { field: 'date', width: 120, title: '日期', totalRowText: '' }
            , {
                field: '', title: '渠道标识', minWidth: 120, templet: function (d) {
                    return d.regsource ? d.regsource.source_key : '';
                }
            }
            , {
                field: '', title: '渠道名称', minWidth: 100, templet: function (d) {
                    return d.regsource ? d.regsource.source_name : '';
                }
            }
            , { field: 'dlcount', width: 200, title: '新增下载次数', totalRowText: '' }
            , { field: 'register', width: 200, title: '新增注册人数', totalRowText: '' }
            , { field: 'valid_user', width: 200, title: '新增有效用户', totalRowText: '' }
            // , { field: 'loggin_user', width: 200, title: '当日登录用户', totalRowText: '' }
            , { field: 'active_user', width: 200, title: '活跃用户', totalRowText: '' }
            , {
                field: '', title: '次日留存率', width: 150, templet: function (d) {
                    return d.retention + '%'
                }
            }
        ]]
        //主要利用回调渲染
        , done: function (res, curr, count) {
            if (res.statis) {
                var total_count = '<strong>共 <span style="color:#1E9FFF;">' + res.statis.count_days + '</span> 天统计</strong>'
                this.elem.next().find('.layui-table-total td[data-field="date"] .layui-table-cell').html(total_count);
                this.elem.next().find('.layui-table-total td[data-field="dlcount"] .layui-table-cell').text(res.statis.dl_count);
                this.elem.next().find('.layui-table-total td[data-field="register"] .layui-table-cell').text(res.statis.register);
                this.elem.next().find('.layui-table-total td[data-field="valid_user"] .layui-table-cell').text(res.statis.valid_user);
                // this.elem.next().find('.layui-table-total td[data-field="loggin_user"] .layui-table-cell').text(res.statis.loggin_user);
                this.elem.next().find('.layui-table-total td[data-field="active_user"] .layui-table-cell').text(res.statis.active_user);

            }
        }
        , page: true
        , limit: 20
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true
    });


    // 渠道统计报表
    table.render({
        elem: '#LAY-source-report-manage'
        , url: '/admin/regsource/report'
        , where: { type: $('.reportTimeChoice .btn_danger').data('type') }
        , totalRow: true
        , cols: [[
            { field: 'date', width: 200, title: '日期', totalRowText: '统计' }

            , { field: 'register', width: 200, title: '新增注册人数', totalRowText: '' }
            , { field: 'valid_user', width: 200, title: '新增有效用户', totalRowText: '' }
            // , { field: 'loggin_user', width: 200, title: '新增登录用户', totalRowText: '' }
            , { field: 'active_user', width: 200, title: '活跃用户', totalRowText: '' }
            , {
                field: '', title: '次日留存率', width: 150, templet: function (d) {
                    return d.retention + '%'
                }
            }
            , { title: '操作', minWidth: 150, align: 'center', fixed: 'right', toolbar: '#table-source-report-operate' }
        ]]
        //主要利用回调渲染
        , done: function (res, curr, count) {
            if (res.statis) {
                this.elem.next().find('.layui-table-total td[data-field="register"] .layui-table-cell').text(res.statis.register);
                this.elem.next().find('.layui-table-total td[data-field="valid_user"] .layui-table-cell').text(res.statis.valid_user);
                // this.elem.next().find('.layui-table-total td[data-field="loggin_user"] .layui-table-cell').text(res.statis.loggin_user);
                this.elem.next().find('.layui-table-total td[data-field="active_user"] .layui-table-cell').text(res.statis.active_user);
            }
        }
        , page: true
        , limit: 20
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true
    });

    //监听工具条
    table.on('tool(LAY-source-report-manage)', function (obj) {
        if (obj.event === 'sourceDetail') {
            let index = layer.open({
                type: 2
                , title: '渠道明细数据'
                , content: '/admin/regsource/everyday?start_time=' + obj.data.date
                , maxmin: true
                , area: ['700px', '500px']
            });
            layer.full(index);
        }
    });


    exports('regsource', {})
});